package net.thxjj.adminServer.websocket.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import net.thxjj.adminServer.entity.Const;
import net.thxjj.adminServer.entity.onenet.OnetEvent;
import net.thxjj.adminServer.service.IDevLogService;
import net.thxjj.adminServer.service.IDevOneNetLogService;
import net.thxjj.adminServer.util.ParameterMap;
import org.apache.ibatis.annotations.One;
import org.eclipse.paho.client.mqttv3.*;

import java.text.SimpleDateFormat;
import java.util.logging.Logger;


public class PushCallback implements MqttCallback {
    private IMqttAsyncClient Client;
    private static final Logger logger = Logger.getLogger(PushCallback.class.getCanonicalName());
    private MqClient mqClient;
    private int reConnTimes = 0;

    private IDevOneNetLogService devOneNetLogService;

    public PushCallback(MqClient client,IDevOneNetLogService devLogService) {
        this.devOneNetLogService = devLogService;
        mqClient = client;
    }

    @Override
    public void connectionLost(Throwable cause) {
        logger.info("connect is losted,and try to reconnect,cause = " + cause.getMessage() );
        cause.printStackTrace();
        while(true){
            if(mqClient.reConnect()){
                break;
            }
            try {
                if(reConnTimes++ > 20){//前20次每秒重连一次
                    Thread.sleep(1000);
                }else{//超过20次后没10s重连一次
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws InvalidProtocolBufferException {
        byte[] payload = message.getPayload();
        OnenetMq.Msg obj = OnenetMq.Msg.parseFrom(payload);
        long at = obj.getTimestamp();
        long msgid = obj.getMsgid();
        String body = new String(obj.getData().toByteArray());

        SimpleDateFormat slf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = slf.format(at);

        logger.info( "time = " + time +
                            ",msg id: " + msgid +
                            ", body: " + body);

        try {
            JSONObject jsonObject = JSON.parseObject(body);
            String prod_key = jsonObject.getJSONObject("sysProperty").getString("productId");
            if(Const.ONENET_PRODUCT_ID.equals(prod_key)){
                JSONObject jsonObject1 =jsonObject.getJSONObject("appProperty");
                String deviceId = jsonObject1.getString("deviceId");
                long timetmp = jsonObject1.getLongValue("dataTimestamp");
                if(body.contains("deviceLifeCycle")){
                    if(body.contains("online")){
                        devOneNetLogService.updateOnlineStatus(true,deviceId,timetmp);
                    }else if(body.contains("offline")){
                        devOneNetLogService.updateOnlineStatus(false,deviceId,timetmp);
                    }
                }else{
                    String event_cot = jsonObject.getString("body");
                    OnetEvent event = new OnetEvent();
                    event.setDeviceId(deviceId);
                    event.setCreateTime(timetmp);
                    event.setEventContent(event_cot);
                    devOneNetLogService.mqAddDevLog(event);
                }
            }

        }catch (JSONException e){
            e.printStackTrace();
        }


    }


    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        Client = token.getClient();
    }


}
